import {miError} from "../utils/exception";
import {simpleGet, simplePost} from "../utils/request";
import {getLoginOpenid} from "./user";
import {showToastError} from "../utils/tool";


export const orderStatus = {
    'unpaid':{title:'待付款', id:'unpaid'},
    'wait':{title:'待发货', id:'wait'},
    'receive':{title:'待收货', id:'receive'},
    'reply':{title:'待评论', id:'reply'},
    'done':{title:'已完成', id:'done'},
    'close':{title:'已关闭', id:'close'},
}

export const payTypeOptions = {
    'wx':{id:'wx', title:'微信支付'},
    'balance':{id:'balance', title:'余额支付'},
}


export const prepareCacheOrder = (order) => {
    // 验证和组装订单数据
    const app = getApp()
    const user = app.globalData.user

    console.log("prepareCacheOrder", order)

    if (typeof order.order_type == 'undefined') throw miError("缺少订单类型")

    if (typeof order.create_type == 'undefined') throw miError("缺少下单方式")

    if (order.create_type == 'cart' && typeof order.cart_ids == 'undefined'){
        throw miError("购物车下单必须有cart_ids")
    }

    if (typeof order.goodsUl == 'undefined') throw miError("缺少商品列表:goodsUl")

    if (typeof order.order_type == 'group') {

        if (typeof order.is_single == 'undefined'){

            throw miError("拼团订单必须指定购买方式：单独购买或者拼单")

        }else if (order.is_single == 0) { // 拼团

            if (typeof order.active_pid == 'undefined') throw miError("拼团订单必须指定发起人ID")

        }

    }

    const orderType = order.order_type
    // 初始化订单信息
    const newOrder = {
        ...order,
        items:[],
        pay_price:0,    // 实际支付金额
        total_price:0, // 订单总金额
        point_price:0,  // 使用的积分总额，
        num:0,  // 订单商品总数
        user_note:'', //备注
        pay_type: 'wx',   // 支付方式,
        is_use_points:0,    // 是否使用积分
    }

    for(let goods of order.goodsUl){

        // 购买的商品数量
        let intNum = parseInt(goods.num)

        if(!intNum || intNum==0) throw miError("缺少商品数量")

        if(goods.spec_type == 2){ // 多规格
            if(!goods.sku)  throw miError("缺少商品规格信息")
        }

        const orderItem = {
            goods_id:goods.id,
            goods_sku_id:goods.spec_type == 2 ? goods.sku.id:0,
            num:intNum,
        }

        newOrder.items.push(orderItem)

    }
    app.globalData.prepareOrder = newOrder
}


export const getCacheOrder = () => {
    const app = getApp()
    const order = app.globalData.prepareOrder || null
    return order
}



export const prepareOrder = async (order) => {
    const {info} = await simplePost("/order/prepare", order)
    return info
}

export const goPay = (order) => {
    // 创建订单缓存信息
    prepareCacheOrder(order)
    // 去支付页面
    wx.navigateTo({
        url: '/pages/user/order_pay/index'
    })
}

const orderService = {

    // 付款
    payment(order){
        return new Promise(async resolve => {
            order = order||{}
            const orderType = order.order_type
            const isSingle = order.is_single

            if (!orderType) throw miError("订单缺少orderType，无法支付")
            if (orderType=='group' && typeof isSingle=='undefined') throw miError("订单缺少isSingle，无法支付")

            const openid = await getLoginOpenid()

            simplePost("/order/pay", {order_id:order.id, openid}).then(r => {

                const {pay_type, pay} = r
                if (pay_type == 'points'){
                    resolve(pay_type)
                }else if (pay_type == 'balance'){
                    resolve(pay_type)
                }else if (pay_type == 'wx'){
                    wx.requestPayment({
                        timeStamp: pay.timeStamp,
                        nonceStr: pay.nonceStr,
                        package: pay.package,
                        signType: pay.signType,
                        paySign: pay.paySign,
                        success: function (success) {

                            resolve(pay_type)

                        },
                        fail: function (e) {
                            console.log("付款失败", e)
                            showToastError("付款失败", {
                                timeout:() => {
                                    wx.redirectTo({
                                        url:'/pages/user/order/index?order_status=unpaid'
                                    })
                                }
                            })
                        }
                    })
                }

            })
        })
    },

    // 订单详情
    async find(id){
        const {info} = await simpleGet("/order/find", {id})
        return info
    },

    // 确认收货
    receive: async (id) => {
        return await simplePost('/order/receive',{
            order_id:id,
        })
    },
    // 取消订单
    async cancel(id){
        return await simplePost('/order/cancel', {id})
    }
}

export default orderService
